package com.tanhua.server.service;

import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;

@Service
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 接口名称：今日佳人
     * 需求描述: 查询缘分值最高的用户。
     * 查询的表：recommend_user
     */
    public ResponseEntity<Object> queryTodayBest() {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();

        //2. 查询当前登陆用户的今日佳人
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);

        //3. 返回vo
        TodayBestVo vo = new TodayBestVo();
        //3.1 根据当前登陆用户（userId）的推荐用户查询
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
        //3.2 对象拷贝，封装用户信息到vo中
        BeanUtils.copyProperties(userInfo,vo);
        //3.3 处理tag属性,在mysql中是字符串："单身,本科,年龄相仿"
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        //3.4 设置缘分值
        vo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：推荐朋友  (首页 推荐用户)
     * 接口路径：GET/tanhua/recommendation
     * 需求描述: 分页查询推荐用户
     * 查询的表：recommend_user
     */
    public ResponseEntity<Object> queryRecommendation(RecommendQueryVo param) {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();

        //2. 分页查询推荐用户
        PageResult pageResult =
                recommendUserApi.queryRecommendation(userId,param.getPage(),param.getPagesize());
        //3. 获取分页查询的结果数据
        List<RecommendUser> list = (List<RecommendUser>) pageResult.getItems();

        //4. 创建返回的vo集合
        List<TodayBestVo> voList = new ArrayList<>();
        //5. 遍历查询结果
        if (!CollectionUtils.isEmpty(list)) {
            for (RecommendUser recommendUser : list) {
                TodayBestVo vo = new TodayBestVo();
                // 根据用户id查询
                UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
                if (userInfo!= null) {
                    BeanUtils.copyProperties(userInfo, vo);
                    if (userInfo.getTags()!=null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                // 设置缘分值
                vo.setFateValue(recommendUser.getScore().longValue());
                // vo添加到集合
                voList.add(vo);
            }
        }

        //6. 把voList设置到pageResult
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：佳人信息 (首页点击推荐用户，查看推荐用户详情)
     * @param recommendUserId
     * @return
     */
    public ResponseEntity<Object> queryPersonalInfo(Long recommendUserId) {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 根据推荐用户id查询
        UserInfo userInfo = userInfoApi.findById(recommendUserId);
        //3. 根据登陆用户id、推荐用户id查询缘分值
        long score = recommendUserApi.queryScore(UserHolder.getUserId(),recommendUserId);

        //4. 返回vo
        TodayBestVo vo = new TodayBestVo();
        BeanUtils.copyProperties(userInfo,vo);
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        // 设置缘分值
        vo.setFateValue(score);

        return ResponseEntity.ok(vo);
    }

    @Reference
    private QuestionApi questionApi;

    /**
     * 接口名称：查询陌生人问题
     * @param userId
     * @return
     */
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        // 根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        String text = question != null ? question.getTxt() : "你喜欢什么？";
        return ResponseEntity.ok(text);
    }

    @Reference
    private UserLocationApi userLocationApi;
    /**
     * 接口名称：搜附近
     */
    public ResponseEntity<Object> searchNear(String gender, Long distance) {
        Long userId = UserHolder.getUserId();
        //1. 调用Api查询(通过dubbo远程调用，要求传入的参数必须实现可序列化接口，如果传入的是对象，
        // 对象以及关联的对象都要实现可序列化接口)
        List<UserLocationVo> userLocationList = userLocationApi.searchNear(userId,distance);
        //2. 封装vo集合
        List<NearUserVo> voList = new ArrayList<>();
        if (userLocationList != null && userLocationList.size()>0) {
            for (UserLocationVo userLocation : userLocationList) {
                // 搜附近，不能包含自己
                if (userId == userLocation.getUserId()) {
                    continue;
                }
                // 根据附近的人搜索
                UserInfo userInfo = userInfoApi.findById(userLocation.getUserId());
                // 匹配性别
                if (!gender.equals(userInfo.getGender())) {
                    continue;
                }

                // 创建并封装返回结果对象
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userLocation.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                // 添加到集合
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }
}
